package com.training.java.redbox;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.training.java.redbox.domain.Customer;
import com.training.java.redbox.domain.Movie;
import com.training.java.redbox.service.MovieService;
import com.training.java.redbox.service.OrdersService;

public class CheckoutAction extends DispatchAction {
	
	public ActionForward checkout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HttpSession session = request.getSession();
		List<Long> cart = (List<Long>) session.getAttribute("cart");
		
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());		
		MovieService service = context.getBean(MovieService.class);
		
		List<Movie> movies = new ArrayList<>();
		
		for(long id : cart){
			
			movies.add(service.findByPrimaryKey(id));
			
		}
		
		request.setAttribute("moviesCart", movies);
		
		return mapping.findForward("checkout");
	}
	
	
	public ActionForward submit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HttpSession session = request.getSession();
		
		Customer customer = (Customer)session.getAttribute("customer");
		
		if(customer!=null){
		
			List<Long> ids = (List<Long>) session.getAttribute("cart");
			
			WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
			OrdersService service = context.getBean(OrdersService.class);
			
			service.submitOrder(ids, customer);
			
			session.invalidate();
			
			return mapping.findForward("thankyou");
		
		}
		else{
			
			request.setAttribute("error", "Please login in order to checkout.");
			return mapping.findForward("checkout");
		}
	}

}
